package com.magima.core.repository;

import java.util.HashMap;

import com.google.gson.annotations.SerializedName;
import com.magima.core.basic.Collection;
import com.magima.core.basic.ICIdGetter;
import com.magima.core.basic.Model;
import com.magima.core.basic.StorageDataListener;
import com.magima.core.basic.option.OnlyRepositoryOption;

public class RepositoryManager {
    private static class LazyHolder{
        private static final RepositoryManager INSTANCE = new RepositoryManager();
    }

    public static RepositoryManager getInstance(){
        return LazyHolder.INSTANCE;
    }

	public class RepositoryVersion {
        @SerializedName("name")
		public String name;
        @SerializedName("version")
		public int version;
	}
	
	private HashMap<String, Integer> targetVersionMap;
	private static Collection<RepositoryVersion> versionCollection;
	
	private Repository mVersionRepository;
	private RepositoryManager(){
		targetVersionMap = new HashMap<String, Integer>();
	}
	
	public void init(Repository repository){
		mVersionRepository = repository;
		versionCollection = new Collection<RepositoryVersion>(RepositoryVersion.class, new ICIdGetter<RepositoryVersion>() {
			@Override
			public String getCId(RepositoryVersion vo) {
				return vo.name;
			}
		});
		versionCollection.setStorage(new RepositoryStorage<RepositoryVersion>(mVersionRepository , RepositoryVersion.class));
		versionCollection.fetch(new StorageDataListener<RepositoryVersion>() {
			@Override
			public void onSuccess(Model<RepositoryVersion> data) {
			}

			@Override
			public void onError(Model<RepositoryVersion> data) {
			}
		});
	}
	
	public void registerTargetVersion(String name, int version){
		targetVersionMap.put(name, version);
	}
	
	public int getRepositoryVersion(String name){
		Model<RepositoryVersion> v = versionCollection.get(name);
		if ( v != null )
			return v.getModel().version;
		return 0;
	}
	
	public void setRepositoryVersion(Repository repository, int version){
		Model<RepositoryVersion> v = versionCollection.get(repository.getName());
		if ( v != null ) {
			v.getModel().version = version;
			v.update(v.getModel(), null, true, new OnlyRepositoryOption());
		} else {
			RepositoryVersion data = new RepositoryVersion();
			data.name = repository.getName();
			data.version = version;
			versionCollection.create(data, null, true, new OnlyRepositoryOption());
		}
	}
	
	public void setRepositoryVersionLatest(Repository repository){
		setRepositoryVersion( repository, getRepositoryTargetVersion(repository));
	}
	
	public int getRepositoryVersion(Repository repository){
		return getRepositoryVersion(repository.getName());
	}
	
	public int getRepositoryTargetVersion(Repository repository) {
		Integer version = targetVersionMap.get(repository.getType());
		if ( version != null )
			return version;
		return 0;
	}
}
